package org.myy.learn.hot.二叉树.最大深度;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.Queue;

@Slf4j
public class Solution {

    //迭代方案
    public static int maxDepth(TreeNode root) {
        if(root == null){return 0;}
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()){
            long size = queue.size(); //1、全弹出   2、下层全入队列
            while (size > 0){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
            depth++;
        }
        return depth;
    }

    /**
     * 根据层序遍历数组构建二叉树
     * @param values 层序遍历序列，null表示空节点
     * @return 根节点
     */
    public static TreeNode buildTree(Integer[] values) {
        if (values == null || values.length == 0 || values[0] == null) {
            return null;
        }

        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int index = 1;
        while (!queue.isEmpty() && index < values.length) {
            TreeNode current = queue.poll();

            // 处理左子节点
            if (index < values.length && values[index] != null) {
                current.left = new TreeNode(values[index]);
                queue.offer(current.left);
            }
            index++;

            // 处理右子节点
            if (index < values.length && values[index] != null) {
                current.right = new TreeNode(values[index]);
                queue.offer(current.right);
            }
            index++;
        }
        return root;
    }

    public static void main(String[] args) {
        Integer[] values = new Integer[]{3,9,20,null,null,15,7};
        TreeNode root = buildTree(values);
        log.info("执行结束，最大深度={}", maxDepth(root));
    }
}
